package com.learning.demos;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author adolphw
 *
 * 集合类不安全问题
 */
public class ContainerNotSafeDemo {


    public static void main(String[] args) {
//        Map<String, String> map = new HashMap<>();
        Map<String, String> map = new ConcurrentHashMap<>();

        for (int i = 0; i < 30; i++) {

            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }

    public static void setUnSafe() {

//        HashSet<> unsafe

//        HashSet<>  hashMap unsafe

//        List<String> list = new ArrayList<>();

//        List<String> vector = new Vector<>();

//        Collection
//        Collections;

//        List<String> list = Collections.synchronizedList(new ArrayList<>());

        new HashSet<>().add("ss");

        List<String> list = new CopyOnWriteArrayList<>();



        for (int i = 1; i < 30; i++) {

            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 5));
                System.out.println(list);
            },String.valueOf(i)).start();

            // Exception in thread "22" Exception in thread "24" Exception in thread "10" java.util.ConcurrentModificationException
            // 并发修改异常 concurrent modification exception

            /**
             * 1 故障现象
             * java.util.ConcurrentModificationException
             *
             * 2 导致原因
             * 并发争抢修改导致，参考花名册修改，一个人正在写，另一个人来抢着写，导致异常
             *
             * 3 解决方案
             *  3.1 new Vector()
             *  3.2 Collections.synchronizedList(new ArrayList<>());
             *  3.3 new CopyOnWriteArrayList<>(); 写时复制---》读写分离思想
             *    public boolean add(E e) {
             *         final ReentrantLock lock = this.lock;
             *         lock.lock();
             *         try {
             *             Object[] elements = getArray();
             *             int len = elements.length;
             *             Object[] newElements = Arrays.copyOf(elements, len + 1);
             *             newElements[len] = e;
             *             setArray(newElements);
             *             return true;
             *         } finally {
             *             lock.unlock();
             *         }
             *     }
             *
             * 4 优化建议
             *CopyOnWriteArrayList
             */


        }
    }
}
